//
//  OrderBuyViewController.m
//  随便点
//
//  Created by MWJ on 15/4/2.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "OrderBuyViewController.h"
#import "orderViewController.h"
#import "OrderFirstRowCell.h"
#import "OrderSecondRowCell.h"
#import "OrderLastCell.h"
#import "DropDown2.h"
#import "ButtonDetailsViewController.h"
#import "AppDelegate.h"
#import "StoreList.h"
#import "LoginViewController.h"
#define Kyydd @"http://www.51anys.com:8080/waimaiwang/order/reserve"

@interface OrderBuyViewController (){
    NSMutableArray *dateArray;  //日期数组
    NSMutableArray *array;   //
    AppDelegate *delegate;
    UIAlertView *_alert;
    NSString *yuyuedic;
}

@end

@implementation OrderBuyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    
    //tableView 顶端不出现空白
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    //隐藏tableview分割线
    self.tableView.separatorStyle=NO;
    
    delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    // 加载tableview
    [self setUp];
    
    [super viewDidLoad];
    

    // Do any additional setup after loading the view.
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -加载tableview
-(void)setUp{
    
    UITableView *tableView =[[UITableView alloc]init];
    CGFloat tableViewX=0;
    CGFloat tableViewY=65;
    CGFloat tableViewW=[UIScreen mainScreen].bounds.size.width;
    CGFloat tableViewH=[UIScreen mainScreen].bounds.size.height;
    tableView.frame=CGRectMake(tableViewX, tableViewY, tableViewW, tableViewH);
    _tableView=tableView;
    _tableView.delegate=self;
    _tableView.dataSource=self;
    [self.view addSubview:tableView];
    

    
}

#pragma mark - cell的数据加载

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    // 第一部分. “餐位类型” “就餐日期” “就餐时间” “就餐人数” “联系人” “联系电话” 的显示
    
    if (indexPath.row == 0) {
        UINib *nib = [UINib nibWithNibName:@"OrderFirstRowCell" bundle:nil];
        [_tableView registerNib:nib forCellReuseIdentifier:@"firstRow"];
        
        static NSString *cellIdentifier=@"firstRow";
        OrderFirstRowCell *cell=[_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        // 餐位类型选择
        DropDown2 *dd1 = [[DropDown2 alloc] initWithFrame:CGRectMake(90, 2, [UIScreen mainScreen].bounds.size.width-105, 30)];
        NSArray *arr=[[NSArray alloc]initWithObjects:@"大厅",@"包间",@"包间优先，大厅也可",nil];
        dd1.tableArray = arr;
        dd1.textField.text =[arr objectAtIndex:0];
        self.restaurant.text = dd1.textField.text;
        [cell addSubview:dd1];
        
        // 就餐日期选择
        //1. 当天日期
        NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *todayTime=[formatter stringFromDate:[NSDate date]];
        self.date.text = todayTime;
        array=[NSMutableArray array];
        //2. 两周之内
        for (int i =1 ; i< 15; i++) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];
            
            NSTimeInterval secondsPerDay= i*24*60*60;
            NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
            
            
            NSString *nextTime=[formatter stringFromDate:tomorrow];
            self.shijian.text = nextTime;
            [array addObject:nextTime];
        }
        
        dateArray=[NSMutableArray arrayWithObjects:todayTime,array, nil];
        //3. 时间选择下拉框
        DropDown2 *dd2=[[DropDown2 alloc] initWithFrame:CGRectMake(90, 37, [UIScreen mainScreen].bounds.size.width-105, 30)];
        dd2.tableArray=array;
        dd2.textField.text=[dateArray objectAtIndex:0];
        [cell addSubview:dd2];
        
        cell.contactTextField.text = delegate._id;
        cell.PhoneTextField.text = delegate._phone;
        
        self.mealsNumber=cell.mealsNumber;
        self.contactTextField=cell.contactTextField;
        self.PhoneTextField=cell.PhoneTextField;
        
        return cell;
    }
    
    // 第二部分： “备注” 的显示
    
    if (indexPath.row == 1) {
        UINib *nib = [UINib nibWithNibName:@"OrderSecondRowCell" bundle:nil];
        [_tableView registerNib:nib forCellReuseIdentifier:@"secondRow"];
        
        static NSString *cellIdentifier=@"secondRow";
        OrderSecondRowCell *cell=[_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        self.beiZhu = cell.beizhu;
        
        return cell;
    }
    
    // 第三部分： “提交订单” 和 “去点菜” button的显示
    
    else {
        UINib *nib = [UINib nibWithNibName:@"OrderLastCell" bundle:nil];
        [_tableView registerNib:nib forCellReuseIdentifier:@"lastRow"];
        
        static NSString *cellIdentifier=@"lastRow";
        OrderLastCell *cell=[_tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        [cell.RowButton1 setTitle:@"提交订单" forState:UIControlStateNormal];
        [cell.RowButton2 setTitle:@"去点菜" forState:UIControlStateNormal];
        // “提交订单”点击事件
        [cell.RowButton1 addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
        // “去点菜”点击事件
        [cell.RowButton2 addTarget:self action:@selector(GoToBuy) forControlEvents:UIControlEventTouchUpInside];
        
        return cell;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 240;
    }
    if (indexPath.row == 1) {
        return 100;
    }
    else{
        return 50;
    }
    
}

-(void)submit{
    if ([delegate._id  isEqual: @""]||delegate._id == nil) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您尚未登陆" delegate:self cancelButtonTitle:@"去登陆" otherButtonTitles:nil, nil];
        _alert = alert;
        [alert show];
    }else if([self.mealsNumber.text isEqualToString:@""]||[self.PhoneTextField.text isEqualToString:@""]||[self.contactTextField.text isEqualToString:@""]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示：" message:@"请输入预定相关信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
    }else{
        [self subscribe];
        
        orderViewController *order = [self.storyboard instantiateViewControllerWithIdentifier:@"orderviewCV"];
        [self.navigationController pushViewController:order animated:YES];
    }
    
}
-(void)subscribe{
    NSString *zt = @"已下单";
    NSString *plat = @"ios";
    NSString *address = [NSString stringWithFormat:@"%@|选择%@;就餐人数:%@",delegate.ShopName,self.restaurant.text,self.mealsNumber.text];
    NSString *times = [NSString stringWithFormat:@"%@%@",self.date.text,self.shijian.text];
    NSURL *url=[NSURL URLWithString:Kyydd];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *postStr=[NSString stringWithFormat:@"name=%@&userId=%@&phone=%@&address=%@&state=%@&shopId=%@&remark=%@&time=%@&platform=%@",self.contactTextField.text,delegate._id,self.PhoneTextField.text,address,zt,delegate.BShopId,self.beiZhu.text,times,plat];
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        yuyuedic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:yuyuedic waitUntilDone:YES];
        delegate.yuyueID = yuyuedic;
    }];

}
-(void)refreshData{
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        LoginViewController *lgvc = [self.storyboard instantiateViewControllerWithIdentifier:@"loginVC"];
        [self.navigationController pushViewController:lgvc animated:YES];
    }
}
-(void)GoToBuy{
    
    //洗车服务店铺类型ID为3
    if ([self.mealsNumber.text isEqualToString:@""]||[self.PhoneTextField.text isEqualToString:@""]||[self.contactTextField.text isEqualToString:@""]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示：" message:@"请输入预定相关信息" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
    }else{
    delegate.splx = @"3";
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ButtonDetailsViewController *buttonDetail=[story instantiateViewControllerWithIdentifier:@"DetailsVC"];
    [self.navigationController pushViewController:buttonDetail animated:YES ];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
